﻿using System.Web;
using NHibernate;
using System.Web.Mvc;
using System.IO;
using System.Drawing;
using Web.Model;

namespace Web.HelperClasses.AvatarService
{
    public class UserAvatarService : AvatarService
    {
        public static string NoAvatarSmall { get; private set; }
        public static string NoAvatarMedium { get; private set; }
        public static string NoAvatarLarge { get; private set; }

        static UserAvatarService()
        {
            NoAvatarSmall = VirtualPathUtility.ToAbsolute("~/Content/img/no_avatar_small.gif");
            NoAvatarMedium = VirtualPathUtility.ToAbsolute("~/Content/img/no_avatar_large.gif");
            NoAvatarLarge = VirtualPathUtility.ToAbsolute("~/Content/img/no_avatar_large.gif");
        }

        [HttpPost]
        public override void UploadNew(int Id, Stream avatarStream)
        {
            var avatarImg = new Bitmap(avatarStream);

            var smallSized = ResizeImage(avatarImg, width: 32);
            var mediumSized = ResizeImage(avatarImg, width: 64);
            var largeSized = ResizeImage(avatarImg, width: 200);

            var user = session.Get<User>(Id);
            string smallEditUrl = yandexFotki.GetOrCreateAlbum("Small avatars");
            string mediumEditUrl = yandexFotki.GetOrCreateAlbum("Medium avatars");
            string largeEditUrl = yandexFotki.GetOrCreateAlbum("Large avatars");
            var small = yandexFotki.UploadPhotoWithName(smallSized, smallEditUrl, user.DisplayName);
            var medium = yandexFotki.UploadPhotoWithName(mediumSized, mediumEditUrl, user.DisplayName);
            var large = yandexFotki.UploadPhotoWithName(largeSized, largeEditUrl, user.DisplayName);

            if (user.Avatar != null)
            {
                RemoveAvatar(user.Avatar);
            }
            user.Avatar = new Avatar
            {
                Small = small,
                Medium = medium,
                Large = large
            };
        }

        public UserAvatarService(ISession session, YandexFotki yandexFotki)
            :base(yandexFotki)
        {
            this.session = session;
        }

        private readonly ISession session;
    }
}